package com.example.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.example.core.constants.Constants;
import com.example.core.constants.HttpConstants;
import com.example.core.utils.ThreadLocalUtil;
import com.example.security.service.TokenService;
import io.jsonwebtoken.Claims;
import io.micrometer.common.util.StringUtils;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lily
 * Date: 2024-11-24
 * Time: 13:45
 */

/**
 * 拦截器
 */
//@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;  //从哪个服务的配置文件中读取，取决于这个bean对象交给了哪个服务的spring容器进行管理。


    /**
     * 进入服务前执行
     * 验证Token
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);  //请求头中获取token
        if(StrUtil.isEmpty(token)){
            return true;
        }
        Claims claims = tokenService.getClaims(token, secret);

        Long userId = tokenService.getUserId(claims);
        ThreadLocalUtil.set(Constants.USER_ID, userId);

        String userKey = tokenService.getUserKey(claims);
        ThreadLocalUtil.set(Constants.USER_KEY, userKey);
        tokenService.extendToken(token, secret);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }

    /**
     * 解析Token
     *
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, "");
        }
        return token;
    }
}